package com.iflytek.cosmo.ocr.support.license.server;

import com.iflytek.cosmo.ocr.support.license.LicenseProcessor;

/**
 * @author <a href=mailto:ktyi@iflytek.com>伊开堂</a>
 * @date 2021/6/29
 */
public abstract class AbstractServerLicenseProcessor extends LicenseProcessor {
    public static final int ENCRYPT_DATA_SIZE = 88;

    /**
     * 授权码子类解密
     *
     * @param license 授权码
     *
     * @return 验证结果
     */
    public abstract ServerLicense decode(String license);

    /** 解密公共部分 */
    public static ServerLicense decodeBaseInfo(String license) {
        try {
            String licenseStr = decrypt(license);
            return new ServerLicense(licenseStr);
        }
        catch (Exception e) {
            System.out.println("解密异常, 验证失败");
            e.printStackTrace();
        }
        return null;
    }

    protected static String decrypt(String license) throws Exception {
        license = license.trim();
        // 分段解密
        StringBuilder sb = new StringBuilder();
        // 每89个字符解密一次
        int times = license.length() / ENCRYPT_DATA_SIZE;
        for (int i = 0; i <= times; i++) {
            int startIndex = i * ENCRYPT_DATA_SIZE;
            int endIndex = startIndex + ENCRYPT_DATA_SIZE;
            endIndex = Math.min(endIndex, license.length());
            if (startIndex == endIndex) {
                continue;
            }

            // 加密
            String substring = license.substring(startIndex, endIndex);
            byte[] decodedBytes = decrypt(base64Decode(substring));
            String str = new String(decodedBytes);
            sb.append(str);
        }
        String decryptedLicense = sb.toString();
        System.out.println("授权内容: " + decryptedLicense);
        return decryptedLicense;
    }

}
